import React, { FC, useEffect, useState } from "react";
import useGetPageInfo from "../../../../hooks/useGetPageInfo";
import { Form, Input, Upload } from "antd";
import type { RcFile, UploadFile, UploadProps } from "antd/es/upload/interface";
import {
  changePageImg,
  resetPageInfo,
} from "../../../../store/pageInfoReducer";
import { useDispatch } from "react-redux";
import ImgCrop from "antd-img-crop";

const { TextArea } = Input;
const PageSetting: FC = () => {
  const pageInfo = useGetPageInfo();
  const [from] = Form.useForm();
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const dispatch = useDispatch();
  useEffect(() => {
    from.setFieldsValue(pageInfo);
  }, [pageInfo]);
  function handleValuesChange() {
    dispatch(resetPageInfo(from.getFieldsValue()));
  }
  const onChange: UploadProps["onChange"] = ({ fileList: newFileList }) => {
    console.log();
    const updatedFileList = newFileList.map((file) => ({
      ...file,
      thumbUrl: file.url,
    }));
    setFileList(updatedFileList);
    if (
      fileList.length > 0 &&
      fileList[0].status == "uploading" &&
      fileList[0].thumbUrl
    ) {
      let thumbUrl = fileList[0].thumbUrl;
      dispatch(changePageImg(thumbUrl));
    } else if (
      fileList.length > 0 &&
      fileList[0].status == "removed" &&
      fileList[0].thumbUrl
    ) {
      dispatch(changePageImg(""));
    }
  };
  return (
    <Form
      layout="vertical"
      initialValues={pageInfo}
      onValuesChange={handleValuesChange}
      form={from}
      style={{ maxWidth: 250 }}
    >
      <Form.Item
        label="问卷标题"
        name="title"
        rules={[{ required: true, message: "请输入标题" }]}
      >
        <Input placeholder="请输入标题" />
      </Form.Item>
      <Form.Item label="问卷描述" name="desc">
        <TextArea placeholder="请输入问卷描述" />
      </Form.Item>
      <Form.Item label="问卷背景图片" name="bgUrl">
        <ImgCrop rotationSlider aspectSlider>
          <Upload
            action="http://image.zclstrive.top/api/index.php"
            listType="picture-card"
            fileList={fileList}
            onChange={onChange}
            maxCount={1}
          >
            {fileList.length < 2 && "切换背景图"}
          </Upload>
        </ImgCrop>
      </Form.Item>
      <Form.Item label="样式代码" name="css">
        <TextArea placeholder="请输入css样式代码" />
      </Form.Item>
      <Form.Item label="脚本代码" name="js">
        <TextArea placeholder="请输入js样式代码" />
      </Form.Item>
    </Form>
  );
};

export default PageSetting;
